<template>
  <div v-if="isShow" class="ui-dialog" id="dialog" @mousemove="pressMove">
    <!-- 头 -->
    <div class="ui-dialog-title" id="dialog-title" @mousedown="pressDown" @mouseup="pressUp">
      <button class="close-btn" @click="closePlayer">X</button>
    </div>
    <!-- 内容区域 -->
    <div class="">
      <aplayer :audio="audio" :lrcType="3" />
    </div>
  </div>
</template>

<script>
import Bus from "@/utils/mitter";

export default {
  name: "globalPlayer",
  data() {
    return {
      isShow: false,
      draggble: false,
      mouseOffsetX: 0,
      mouseOffsetY: 0,
      audio: {
        name: '',
        artist: '无',
        url: '',
        cover: '', // prettier-ignore
        lrc: '',
      },
    } // end return
  },
  mounted() {
    Bus.on('openPlayer', audio => {
      this.isShow = true;
      this.audio = audio;
    })
  },
  methods: {
    //获取对象
    getElement(id) {
      return document.getElementById(id);
    },
    //按下鼠标, 设置盒子为可移动
    pressDown(e) {
      this.mouseOffsetX = e.pageX - this.getElement('dialog').offsetLeft;
      this.mouseOffsetY = e.pageY - this.getElement('dialog').offsetTop;
      this.draggble = true;
    },
    // 按下后移动时, 移动盒子
    pressMove(e) {
      // 鼠标当前位置
      let mouseX = e.pageX;
      let mouseY = e.pageY;
      // 新位置
      let moveToX = 0;
      let moveToY = 0;

      // 如果可以移动
      if (this.draggble) {
        moveToX = mouseX - this.mouseOffsetX;
        moveToY = mouseY - this.mouseOffsetY;

        let pageWidth = document.documentElement.clientWidth;
        let pageHeight = document.documentElement.clientHeight;

        let dialogWidth = this.getElement('dialog').offsetWidth;
        let dialogHeight = this.getElement('dialog').offsetHeight;

        let maxX = pageWidth - dialogWidth;
        let maxY = pageHeight - dialogHeight;

        moveToX = Math.min(maxX, Math.max(0, moveToX));
        moveToY = Math.min(maxY, Math.max(0, moveToY));

        this.getElement('dialog').style.left = moveToX + "px";
        this.getElement('dialog').style.top = moveToY + "px";
      }
    },
    // 松开鼠标, 盒子停止移动
    pressUp(){
      this.draggble = false;
    },
    // 关闭
    closePlayer(){
      this.isShow = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.ui-dialog {
  width: 380px;
  height: auto;
  position: absolute;
  z-index: 1000;
  right: 10px;
  bottom: 10px;
  background-color: #fff;
}

.ui-dialog-title {
  height: 12px;
  font-size: 10px;
  background: rgba(255, 255, 255, 0.99);
  cursor: move;
  user-select: none;
}

.ui-dialog-content {
  padding: 15px 20px;
}

.ui-mask {
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.4;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 900;
  display: none;
}
.close-btn{
  position: absolute;
  right: 5px;
  top: 0px;
  background: #55d7cb3d;
  border: 0px;
  color: #585050d6;
  border-radius: 3px 3px 0px 0px;
}
</style>
